<template>
  <div class='container'>
    <div class='side-bar'>
      <div class='logo'>
        <el-image :src='logoImg'/>
        <h3 style='height: 50px;line-height: 50px;padding:0 10px;color: #fffcfc'>健身管理系统</h3></div>
      <div class='menu'>
        <el-menu
          active-text-color="#ffd04b"
          background-color="#2F91C2"
          class="el-menu-vertical-demo"
          :default-active="active"
          text-color="#fff"
          style='height: 100%;'
          :router='true'
        >
          <template v-for='(menu,index) in showMenus' :key='index'>
            <el-sub-menu v-if='menu.children' :index='menu.path'>
                <template #title>
                  <Icon class='menu-icon' :icon='menu.icon'/>
                  <span>{{menu.title}}</span>
                </template>
              <el-menu-item v-for='(mItem,mIndex) in menu.children' :index='mItem.path' :key='mIndex'>
                <Icon class='menu-icon' :icon='mItem.icon' />
                {{mItem.title}}
              </el-menu-item>
            </el-sub-menu>
            <el-menu-item v-else :index='menu.path'>
              <Icon class='menu-icon' :icon='menu.icon' />
              {{menu.title}}
            </el-menu-item>
          </template>
        </el-menu>
      </div>
    </div>
    <div class='main'>
      <div class='header'>
        <el-breadcrumb class="bread-crumb" separator="/">
          <transition-group name="breadcrumb">
            <el-breadcrumb-item
              v-for="(item,index) in breadcrumbData"
              :key="item.path"
            >
              <!-- 不可以点击项 -->
              <span
                v-if="index === breadcrumbData.length - 1"
                class="no-redirect"
              >{{ item.meta.title }}</span
              >
              <!-- 可以点击项 -->
              <a v-else class="redirect" @click.prevent="onLinkClick(item)">{{
                  item.meta.title
                }}</a>
            </el-breadcrumb-item>
          </transition-group>
        </el-breadcrumb>
        <el-link type="primary" target="_blank" href="/data-visual" style="color: #000;">可视化数据</el-link>
        <div class='user-info'>

          <div style="text-align: center;color: #835a1d;line-height: 50px;margin-right: 10px;">{{username}}</div>
          <!--          <el-divider direction="vertical"></el-divider>-->
          <div class='logout' @click='logout'>退出登录</div>
        </div>
      </div>
      <div class="content">
        <el-tabs v-model="tab.editableTabsValue" type="card" class="demo-tabs"
                 :closable='tab.editableTabsValue!=="dashboard" '
                 @tab-remove="removeTab" @tab-change="changeTab">

          <el-tab-pane v-for="(item,index) in tab.editableTabs" :key="item.name" :label="item.title"
                       :name="item.name">
            <router-view ></router-view>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>

</template>

<script lang="ts" setup>
import { onMounted, ref, watch, onBeforeMount,createVNode } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Document, Menu as IconMenu, Location, Setting,ReadingLamp,Coin,Goods,User,CollectionTag,Magnet,DataBoard,
  House, Avatar,HomeFilled,UserFilled,GoodsFilled,CreditCard,WalletFilled,Iphone,ForkSpoon,PriceTag,Failed,SetUp,
  List,DocumentCopy}
  from '@element-plus/icons-vue'
import logoUrl from '../assets/ego-mall.png'
import { ArrowRight } from '@element-plus/icons-vue'
import logo from '@/assets/logo.png'
import {tabsStore} from '@/stores/tabs'
import {getCurrRoles} from '@/api/sys/user'
import {menus} from '@/config/menus'
import storage from '@/utils/storage'

const main = ref('首页');

const logoImg = ref(logo);
const route = useRoute();
const router = useRouter();
const tab = tabsStore();
const active = ref('');

const showMenus = ref([]);
const user = ref({})
// 生成数组数据
const breadcrumbData = ref([]);
const getBreadcrumbData = () => {
  breadcrumbData.value = route.matched.filter((item) => {
    return item.name && item.path;
  });
};

const removeTab = (targetName: string) => {
  console.log('removeTab:=============>targetName:',targetName,',editableTabsValue:',tab.editableTabsValue);
  if (targetName !== 'home' && targetName !== 'dashboard') {//判断点击是否为首页
    if (tab.editableTabsValue === targetName) {
      console.log('tab.editableTabs----->',tab.editableTabs);
      tab.editableTabs.forEach((tabs, index) => {
        if (tabs.name === targetName) {
          const nextTab = tab.editableTabs[index + 1] || tab.editableTabs[index - 1]
          if (nextTab) {
            router.push({name:nextTab.name})
          }
        }
      })
    }
    //过滤掉当前点击的tab标签
    tab.editableTabs = tab.editableTabs.filter((tab) => tab.name !== targetName)
  }

}
const changeTab = (targetName: string)=>{
  console.log('history_state:',history.state)
  router.push({name: targetName,state:history.state})
}

// 监听路由发生改变时触发
watch(
  route,
  () => {
    getBreadcrumbData();
    const arr = []
    console.log('tabs:',tab.editableTabs)
    tab.editableTabs.forEach(item => {
      if(item.title !== '首页'){
        arr.push(item.title)
      }
    });
    const res = arr.indexOf(route.meta.title)
    console.log('match:',route.meta.title,',result:',res,',arr:',arr);
    if(res==-1 && route.meta.title !== '首页'){
      tab.editableTabs.push({
        title: route.meta.title,
        name: route.name,
      })
    }
    tab.editableTabsValue = route.name
    active.value=route.path
  },
  {
    immediate: true,
  }
);
// 处理点击事件
const onLinkClick = (item) => {
  router.push(item.path);
};
function logout(){
  storage.removeItem('accessToken');
  storage.removeItem('roles')
  storage.removeItem('user')
  router.push('/login')
}

const roles = ref({roles: undefined})
onBeforeMount(()=>{
  getCurrRoles().then(res => {
    if(res.code === '00000'){
      storage.setItem('roles',res.data);
      roles.value.roles = res.data;
      let currUserRoles = res.data[0];
      showMenus.value = [];

      // if(currUserRoles.includes('admin')){
      //   showMenus.value = menus;
      // }else{
        const deepCloneMenus: typeof menus = JSON.parse(JSON.stringify(menus));
        deepCloneMenus.forEach((item,index)=>{
          const perms = item.perm || [];
          const tmpList = perms.filter(perm => perm === 'none' || currUserRoles === perm);
          if(tmpList && tmpList.length > 0){
            const subItems = item.children;
            if(subItems){
              for(let i=0;i<subItems.length;i++){
                const subPerms = subItems[i].perm || [];
                const subTmpList = subPerms.filter(p => p === 'none' || currUserRoles === p);
                if(!subTmpList || subTmpList.length === 0){
                  subItems.splice(i,1);
                  i--
                }
              }
            }
            showMenus.value.push(item);
          }
        })
        // console.log("---****>>>" + showMenus.value[0].title);
      // }


    }
  })
})
const username = ref('')
onMounted(()=>{
  const accessToken = storage.getItem("accessToken")
  console.log('accessToken:',accessToken)
  if(!accessToken){
    window.location.href = '/login'
  }
  user.value = JSON.parse(storage.getItem("user"))
  username.value = user.value.username
  console.log('=====>user',user);
  if(route.name !=='home' && route.name !== 'dashboard' && tab.editableTabsValue !== route.name){
    tab.editableTabs.push({
      title: route.meta.title,
      name: route.name,
    })
    tab.editableTabsValue = route.name
    active.value=route.path
  }

})
</script>

<style scoped>
.container{
  position: absolute;
  left:0;
  top:0;
  width: 100%;
  height: 100%;
  display: flex;
}
.side-bar{
  display: flex;
  width: 220px;
  flex-direction: column;
  height: 100vh;
}
.logo{
  /*flex-flow: column;*/
  display: flex;
  background-color: #5dc9ea;
  width: 100%;
  height: 50px;
  justify-content: center;
}
.menu{
  flex-grow: 1;
  width: 220px;
}
.header{
  display: flex;
  background-color: #5dc9ea;
  border-bottom: 1px solid #ccc;
  height: 50px;
  width: 100%;
  justify-content:space-between;
}
.bread-crumb{
  text-align: center;
  line-height: 50px;
  margin-left: 20px;
  color: #0e0b0b;
}
.user-info{
  width: 400px;
  display: flex;
  justify-content: center;

  /*background-color: black;*/
}
.logout{
  color: #423e3e;
  line-height: 49px;
  cursor: pointer;
}
.logout:hover{
  color: #4c6ccc;
}
.tags{
  height: 20px;
  width: 100%;
  padding: 0;
  border-bottom: 1px solid #000;
  background-color: #fff;
}
.main{
  background-color: #ccc;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.content{
  background-color: #fffcfc;
  width: 100%;
  min-height: 93%;
  /*height: 100%;*/
  /*border: 1px solid #8b093f;*/
  /*border-radius: 10px;*/
  margin: 5px 5px;
  box-shadow: rgba(0, 0, 0, 0.2) 0px 12px 28px 0px,
  rgba(0, 0, 0, 0.1) 0px 2px 4px 0px,
  rgba(255, 255, 255, 0.05) 0px 0px 0px 1px inset;
}
.menu-icon{
  width: 1.5em;
  height: 1.5em;
  margin-right: 8px;
}
</style>
